<script setup>
import { onBackPress, onHide, onLoad, onReady, onUnload } from "@dcloudio/uni-app";
import { computed, onMounted, ref } from "vue";
import { useUserStore } from "@/stores/userStore.js"
import { clothesDelDjangoApi } from "@/apis/clothes.js";
// 创建camera对象
// 用于保存拍下图片的src
const src = ref("");
const userWidth = ref("");
const userHeight = ref("");
const isVisible = ref(false);
const imageSrc = ref("");
let socketTask = null;
const type = ref("");
const imageId = ref("");
const camera = uni.createCameraContext();
const isNeed = ref(false);

onLoad((options) => {
 type.value = options.type;
  if (options.type === "scan") {
    isVisible.value = false
    // 用户已经同意小程序使用摄像头
  // 创建WebSocket连接
  socketTask = uni.connectSocket({
    url: 'ws://127.0.0.1:6999/test/123/',
    success: () => {}
  });

  // 监听WebSocket连接打开事件
  socketTask.onOpen( async() => {
    uni.onSocketMessage((res) => {
      imageSrc.value = JSON.parse(res.data).img_url
    })
    setInterval(async () => {
      const res = await camera.takePhoto({ quality: "low" });
      const base64 = await getImageBase64_readFile(res.tempImagePath)
        socketTask.send({
          data: base64
        });
    }, 300)

  });
 }
 if (type.value === "photo") { 
  isVisible.value = true
}
})

const needPhoto = () => {
  isVisible.value = true
  isNeed.value = false
}

const deletePhoto = async() => {
  isVisible.value = true
  isNeed.value = false
  const res = await clothesDelDjangoApi(imageId.value)
}

onUnload(() => {
  if (type.value === "scan") {
    socketTask.close({
      code: 1000, // 关闭连接的状态码，默认值1000，表示正常关闭
      reason: '关闭连接', // 关闭的原因，可选
      success: () => {
      },
    });
  }
})

const takePhoto = () => {
  if (type.value === "photo") { 
    isVisible.value = false
    isNeed.value = true
    camera.takePhoto({
      quality: "low",
      success: async (res) => {
        const userStore = useUserStore();
        const user = userStore.getUserInfo()
        const imgRes = await uni.uploadFile({
              url: `http://localhost:6999/change/upload/${user.userId}`,
              filePath: res.tempImagePath,
              name: 'file',
              header: {
                  'token': `${uni.getStorageSync('token')}`
              }
        });
        if (JSON.parse(imgRes.data)[0]) {
          imageSrc.value = JSON.parse(imgRes.data)[0].imgUrl
          imageId.value = JSON.parse(imgRes.data)[0].imgId
        } else {
          imageSrc.value = '../../static/images/noPhotos.png'
          isVisible.value = true
          isNeed.value = false
        }
      }
    })
  }
}

onMounted(() => {
  const systemInfo = uni.getSystemInfoSync();
  userWidth.value = systemInfo.screenWidth + "px";
  userHeight.value = systemInfo.screenHeight + "px";
});
const takePhotos = ref({
  width: userWidth,
  height: userHeight,
  background: 'white',
});

const getImageBase64_readFile = async (tempFilePath) => {
  return await new Promise(resolve => {
    //获取全局唯一的文件管理器
    wx.getFileSystemManager()
      .readFile({ //读取本地文件内容
        filePath: tempFilePath, // 文件路径
        encoding: 'base64', // 返回格式
        success: ({ data }) => {
          return resolve(data);
        }
      });
  });
}

</script>
<template>
  <view :style="takePhotos">
    <camera device-position="back" flash="off" style="width: 100%; height: 50%;"></camera>
    <image style="width: 100%; height: 50%;" class="tempShow" :src="imageSrc"></image>
    <uni-icons type="circle-filled" size="50" class="takeBtn" @click="takePhoto" v-show="isVisible"></uni-icons>
    <uni-icons type="checkmarkempty" size="30" class="checkmarkempty" @click="needPhoto" v-show="isNeed"></uni-icons>
    <uni-icons type="closeempty" size="30" class="closeempty" @click="deletePhoto" v-show="isNeed"></uni-icons>
  </view>
</template>
<style scoped>
.takeBtn {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-100%);
  z-index: 999;
}

.checkmarkempty {
  position: absolute;
  bottom: 5%;
  left: 10%;
  /* transform: translateX(-50%) translateY(-100%); */
  z-index: 999;
}
.closeempty {
  position: absolute;
  bottom: 5%;
  right: 10%;
  /* transform: translateX(-50%) translateY(-100%); */
  z-index: 999;
}

</style>
